package com.udp.nml.example;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UDPPortSpecifyingServer 
{
	static Logger logger = LoggerFactory.getLogger(UDPPortSpecifyingServer.class);
	
	private int port;
	
	private NioDatagramAcceptor acceptor;
	
	private IoHandlerAdapter ioHandler;
	public static int DEFAULT_PORT = 56000;
	
	public static void main(String[] args)
	{
		UDPPortSpecifyingServer server = new UDPPortSpecifyingServer(DEFAULT_PORT, new UDPHandler());
		server.setup();
	}
	
	public UDPPortSpecifyingServer(int port, IoHandlerAdapter ioHandler)
	{
		this.port = port;
		this.ioHandler = ioHandler;
	}
	
	public void setup()
	{
		logger.info(">>> setup");
		
		try 
		{
			acceptor = new NioDatagramAcceptor();
			
			acceptor.setHandler(ioHandler);
	
			DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
			
			chain.addLast("logger", new LoggingFilter());
	
			DatagramSessionConfig dcfg = acceptor.getSessionConfig();
			
			dcfg.setReuseAddress(true);
			
			acceptor.bind(new InetSocketAddress(port));
			
		
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		logger.info("<<< setup");
	}


	public void stop()
	{
		if (acceptor != null)
		{
			acceptor.unbind();
			acceptor.dispose();
		}
	}
	
	public boolean isActive()
	{
		boolean isActive = false;
		
		if (acceptor != null)
		{
			isActive = acceptor.isActive();
		}
		
		return isActive;
	}
	
	
	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public NioDatagramAcceptor getAcceptor() {
		return acceptor;
	}

	public void setAcceptor(NioDatagramAcceptor acceptor) {
		this.acceptor = acceptor;
	}

	public IoHandlerAdapter getIoHandler() {
		return ioHandler;
	}

	public void setIoHandler(IoHandlerAdapter ioHandler) {
		this.ioHandler = ioHandler;
	}
}
